package com.jd.org.controller;

import com.jd.basic.util.AjaxsResult;
import com.jd.basic.util.PageList;
import com.jd.org.domain.Department;
import com.jd.org.query.DepartmentQuery;
import com.jd.org.service.IDeprtmentService;
import com.jd.system.annotation.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Api(value = "部门",description = "部门")
@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDeprtmentService deprtmentService;

    /**
     * 查询
     * @param id
     * @return
     */
    @ApiOperation(value = "单个查询")
    @GetMapping("/{id}")
    public Department findOne(@PathVariable("id")Long id){
        return deprtmentService.loadById(id);
    }
    @GetMapping
    @ApiOperation(value = "查询所有")
    public List<Department> findAll(){
        return deprtmentService.loadAll();
    }

    // 删除

    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "部门删除",sn ="department:delete")
    public AjaxsResult remove(@PathVariable("id")Long id){
        try {
            deprtmentService.remove(id);
            return new AjaxsResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxsResult(false,"删除失败");
        }
    }

    /**
     * 修改和添加
     * @param department
     * @return
     */

    @ApiOperation(value = "修改和添加")
    @PutMapping
    public AjaxsResult save(@RequestBody Department department){
        try {
            if (department.getId()==null){
                // 添加
                deprtmentService.save(department);

            }else {
                // 修改
                deprtmentService.update(department);
            }
            return new AjaxsResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxsResult(false,"操作失败");
        }
    }

    /**
     * 分页查询
     * PageList<Department>返回参数：需要数据和总条数
     *@PathVariable DepartmentQuery departmentQuery：获取路径的当前页和显示的条数
     */

    @ApiOperation(value = "分页查询")
    @PostMapping // 匹配前端url地址
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        return deprtmentService.queryPage(departmentQuery);
    }

    // 批量删除
    @ApiOperation(value = "批量删除")
    @PatchMapping
    public AjaxsResult patchRemove(@RequestBody List<Long> ids){
        try {
            deprtmentService.patchRemove(ids);
            return new AjaxsResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxsResult(false,"删除失败");
        }
    }

    @ApiOperation(value = "查询部门树")
    @GetMapping("/deptTree")
    public List<Department> deptTree(){
        return deprtmentService.deptTree();
    }
}
